package com.cameron.oos.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.cameron.oos.service.OssService;
import com.cameron.oos.util.OssConstants;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;


/**
 * @author cameron
 */
@Service
@Slf4j
public class OssServiceImpl implements OssService {

    @Override
    public String uploadAvatar(MultipartFile file) {

        String endpoint = OssConstants.END_POINT;
        String accessKeyId = OssConstants.KEY_ID;
        String accessKeySecret = OssConstants.KEY_SECRET;
        String bucketName = OssConstants.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String url = null;
        try {
            InputStream inputStream = file.getInputStream();
            //防止文件重名
            String origin = file.getOriginalFilename();
            String fileType = origin.substring(origin.lastIndexOf('.'));
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //将图片以日期的方式分类
            //例：/2022/6/15/cam.jpg
            String now = new DateTime().toString("yyyy/MM/dd");
            String fileName = "res-img/" + now + "/" + uuid + fileType;
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);
            url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
